package com.dingtalk.h5app.quickstart.service;

import com.dingtalk.h5app.quickstart.domain.entity.Cellwidget;
import com.dingtalk.h5app.quickstart.domain.entity.Widget;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;

import java.util.*;
@Service("JDYInterface")

public class DingdingSerivceImpl implements JDYInterface {

    private List<Widget> getWidgetListFromAPIJSON(List<Map<String, Object>> widgets, String appId, String entryId) {
        ObjectMapper mapper=new ObjectMapper();
        System.out.println("表单字段：");
        List<Widget> widgetList=new ArrayList<>();
        for (Map<String, Object> widgetmap : widgets) {
            System.out.println(widgetmap);
            Widget widget=new Widget();
            //widget.setId(UUID.randomUUID().toString());
            widget.setAppId(appId);
            widget.setEntryId(entryId);
            widget.setLabel(widgetmap.get("label").toString());
            widget.setName(widgetmap.get("name").toString());
            widget.setType(widgetmap.get("type").toString());
            if(!isMapofsubform(widgetmap)){
                System.out.println("这个是正常的表单字段--------------------------");
                System.out.println(widget+"\r\n");
            }else {
                System.out.println("这个是表格的表单字段--------------------------");
                String value=widgetmap.get("items").toString();
                System.out.println(value+"\r\n");
                String json= convertStringToJsonString(value);
                System.out.println("Json:"+json+"\r\n");
                List<Cellwidget> cellwidgetList=new ArrayList<>();
                try {
                     cellwidgetList = mapper.readValue(json, new TypeReference<List<Cellwidget>>() {});
                }catch (Exception ex){

                }

                for(Cellwidget cellwidget:cellwidgetList){
                    //cellwidget.setWidgeRelation(widget);
                    cellwidget.setWidget(widget);
                    widget.getCellwidgetList().add(cellwidget);
                }
            }
            widgetList.add(widget);
        }
        handleWidgetReplace(widgetList);
        return widgetList;
    }
    /*
    * 原来id为null，现在替换为name值。也是不重复的
    * */
    private void handleWidgetReplace(List<Widget> widgetList){
        for(Widget widget:widgetList){
            widget.setId(widget.getName());
            for(Cellwidget cellwidget:widget.getCellwidgetList()){
                cellwidget.setId(cellwidget.getName());
            }
        }
    }

    private void createLoopFieldsql(List<Widget> nontablelist) {
    }

    private  String convertStringToJsonString(String value) {
        //普通字符串转为Json格式。原来的字符串上是=，转为json为：原来字符串上没有“”，后来都为双引号
        //https://blog.csdn.net/qq_45641590/article/details/105549770
        //换等号后面的
        String jsonArrayValueStr = value.replace("}, {", "},{");
        jsonArrayValueStr = jsonArrayValueStr.replace("=", "=\"");
        jsonArrayValueStr = jsonArrayValueStr.replace(", ", "\", ");
        jsonArrayValueStr = jsonArrayValueStr.replace("}", "\"}");
        //换等号
        jsonArrayValueStr=jsonArrayValueStr.replace("=",": ");

        //换等号前面的
        String x1=jsonArrayValueStr.replace("{name:","{"+"\""+"name"+"\""+":");
        String x2=x1.replace("label:","\""+"label"+"\""+":");
        String x3=x2.replace("type:","\""+"type"+"\""+":");

        //jsonArrayValueStr.replace("label","\""+"label"+"\""); 直接进行replace不行，必须转到一个新的字符串中
        //参考 https://blog.csdn.net/thinkingmyself/article/details/88179267

                /*jsonArrayValueStr.replace("label","\""+"label"+"\"");
                jsonArrayValueStr.replace("type","\""+"type"+"\"");*/
        //System.out.println("转换后的JSON数组字符串："+jsonArrayValueStr);
        System.out.println("转换后的JSON数组字符串："+x3);

        //原文链接：https://blog.csdn.net/weixin_42558001/article/details/103857219
        //   Map<String, Object> subformmap = (Map<String, Object>) mapper.readValue(json, Object.class);
        return x3;
    }

    private  boolean isMapofsubform(Map<String,Object> widget){
        boolean subform=false;
        Collection<Object> values=widget.values();
        Iterator iter = values.iterator();
        //使用hasNext()方法判断是否有下一个元素
        while(iter.hasNext()){
            //使用next()方法返回元素
            String str = (String)iter.next();
            if(str.equalsIgnoreCase("Subform")){
                subform=true;
                break;
            }
        }
        return subform;
    }
    @Override
    public List<Widget> getWidgetAndConvertEntity(String appId, String entryId, String apiKey) {

       /* APIUtilsTransfer api = new APIUtilsTransfer(appId, entryId, apiKey);
        // 获取表单字段，这个与WebHook的Json有一点差别
        List<Map<String, Object>> widgets = api.getFormWidgets();
       // JDYInterface jdySerivce=new JDYSerivceImpl();
        List<Widget> widgetList=getWidgetListFromAPIJSON(widgets,appId,entryId);
        return widgetList;*/
       return  null;
    }
}
